<template>
  <div class="dcpeditor-wrapper">
    <div class="dcpeditor-left">
      <compTree :contentData="contentData" :currentContentId="currentContentId" @tapTreeItem="tapComponent"></compTree>
      <compList :componentsType="componentsType" @addNewComp="addNewComp"></compList>
    </div>
    <div class="dcpeditor-center" ref="dcpeditorCenter">
      <div class="dcpeditor-center-tool">
        <div class="dcpeditor-center-tool-zoom">
        显示比例：<el-slider style="width:200px;margin-right:10px;" :step="20" v-model="zoom" :format-tooltip="zoomFormatTip" :max="400" :min="20" ></el-slider> {{zoom + '%'}}
        </div>
      </div>
      <div class="dcpeditor-center-main" @mousemove="moveView" @mouseout="moveoutView">
        <div class="rodtop-position" @click.stop="tapResetPosition"></div>
        <canvas class="rodtop" ref="rodTop"></canvas>
        <canvas class="rodleft" ref="rodLeft"></canvas>
        <div class="rodtop-mouse-line" ref="rodTopMouse"></div>
        <div class="rodleft-mouse-line" ref="rodLeftMouse"></div>
        <div class="dcpeditor-center-view" ref="dcpeditorCenterView">
          <div class="dcpeditor-center-phone" :style="{width:phoneWidth,zoom:zoom / 100}" >
          <compPhoneTop></compPhoneTop>
          <draggable class="phone-wrapper" animation="400" v-model="contentData" group="phone" :options="dragOptions" :move="onMove" @start="isDragging=true" @end="isDragging=false">
            <transition-group>
              <div v-for="(item,index) in contentData" :key="item.id"  class="phone-item" :class="{'phone-item-active':item.id == formData.id}" @click="tapComponent(index)">
                <div class="swiper" v-if="item.type == 'swiper'">
                  <el-carousel height="150px" v-if="item.data && item.data[item.id] && item.data[item.id].list">
                    <el-carousel-item v-for="(swiperItem,swiperIndex) in item.data[item.id].list" :key="swiperIndex">
                      <img :src="swiperItem.url" style="width:100%;height:150px;">
                    </el-carousel-item>
                  </el-carousel>
                  <div v-else class="no-img">【轮播图】请上传图片</div>
                </div>
                <div class="image" v-if="item.type == 'img'" :style="{width:item.width / 2 +'px',height:item.height / 2 +'px'}" >
                  <img :src="item.data[item.id].url" class="comp-content-img" v-if="item.data && item.data[item.id]">
                  <img v-else src="~img/pic_default.svg" class="comp-content-img" />
                </div>
              </div>
            </transition-group>
          </draggable>
        </div>
        </div>
      </div>     
    </div>
    <div class="dcpeditor-right">
      <div class="editor-header">组件属性</div>
      <el-form :model="formData" class="editor-content" ref="attrForm" v-if="formData.id">
        <el-row class="dcpeditor-form-group dcpeditor-form-name-wrapper">
          <el-col :span="12">
            <div class="dcpeditor-form-name" @click="tapCompName" v-if="isEditCompName !== true">{{formData.name}}</div>
            <el-input size="mini" v-model="formData.name" ref="compNameInput" @blur="blurCompName" v-else></el-input>
          </el-col>
        </el-row>
        <el-row class="dcpeditor-form-group">
          <el-col :span="12">
            <span class="dcpeditor-form-label dcpeditor-form-slider">宽度</span>
            <el-input-number size="mini" style="width:96px;"  v-model="formData.width" controls-position="right" :min="1" :max="750"></el-input-number>
          </el-col>
          <el-col :span="12">
            <span class="dcpeditor-form-label dcpeditor-form-slider">高度</span>
            <el-input-number size="mini" style="width:96px;" v-model="formData.height" controls-position="right" :min="1"></el-input-number>
          </el-col>
        </el-row>
        <el-row class="dcpeditor-form-bottom">
          <el-button class="dcpeditor-form-submit" type="primary">保存</el-button>
        </el-row>
      </el-form>
    </div>
  </div>

</template>
<script>
import draggable from "vuedraggable";
import compTree from './compTree';
import compList from './compList';
import compPhoneTop from './compPhoneTop';
export default {
  name: "custpageEditor",
  components: {
    draggable,
    compTree,
    compList,
    compPhoneTop
  },
  created(){
    
  },
  mounted(){
    this.init();

    window.onresize = () => {
      this.init();
    }
    let page = this;
    window.addEventListener('mousewheel', function(event){
        if (event.ctrlKey === true || event.metaKey) {
          event.preventDefault();
          if (event.deltaY > 0){
            if (page.zoom <= 20) return;
            page.zoom -= 20;
          } else {
            page.zoom += 20;
          }
        }
    },{ passive: false});

    //firefox
    window.addEventListener('DOMMouseScroll', function(event){
        if (event.ctrlKey === true || event.metaKey) {
            event.preventDefault();
        }
    },{ passive: false});
  },
  data() {
    return {
      viewWidth:0,
      viewHeight:0,
      phoneWidth:375,
      zoom:100,
      componentsType:[
        {label:'容器',type:'view',iconClass:'el-icon-house',valueForm:[]},
        {label:'图片',type:'img',iconClass:'el-icon-picture-outline',height:300,width:750},
        {label:'轮播图',type:'swiper',iconClass:'el-icon-orange',attrForm:[
          {field:'url',label:'上传图片',type:'swiper',limit:9,placeholder:''},
        ]},
        {label:'视频',type:'product',iconClass:'el-icon-film'},
        {label:'产品',type:'product',iconClass:'el-icon-goods'},
        {label:'九宫格',type:'product',iconClass:'el-icon-s-grid'},
        {label:'悬浮穿',type:'product',iconClass:'el-icon-s-promotion'},
        {label:'文本',type:'product',iconClass:'el-icon-notebook-2'},
      ],
      contentData:[],//中间预览区域的内容数据
      autoId:1,//保证组件循环的key不重复的递增id（暂时无用）
      editable: true,//中间拖动去是否可拖动
      isDragging: false,
      delayedDragging: false,
      attrForm:[],//当前选中内容的表单列表显示
      attrFormData:{},
      formData:{},//当前选中内容表单的数据值
      fileList:[],//轮播器、图片等上传组件用到的文件列表
      hrefOptions:[
        {label:'外链地址',value:'url'},
        {label:'产品详情',value:'product_detail'},
        {label:'产品列表',value:'proudct_list'}
      ],
      activeHrefOptions:'',
      isEditCompName:false,//是否正在编辑组件名称
      currentContentId:0//当前选中得是哪个组件ID得属性
    };
  },
  methods: {
    test(val){
      console.log(val);
    },
    init(){
      this.initView();
    },
    initView(){
      this.viewWidth = this.$refs.dcpeditorCenter.clientWidth;
      this.viewHeight = this.$refs.dcpeditorCenter.clientHeight;
      this.initRod();
    },
    initRod(){
      
      let lineSpace = 5 ;//标尺精度，5px一个点
      const rodEmptySize = 25;//标尺开始位置，左上方留一个等宽空位置,需要为lineSpace倍数
      const rodLineSizeShort = 4;//标尺-短刻度的长度
      const rodLineSizeLong = 8;//标尺-长刻度的长度
      const rodLineSizeText = 15;//标尺-刻度字的大小
      const initMarginTop = 100;//展示区域距离顶部标尺的空白区域高度，即左侧标尺0刻度开始的地方

      const viewWidth = 10000;
      const viewHeight = 10000;

      this.$refs.dcpeditorCenterView.style.width = viewWidth + 'px';
      //this.$refs.dcpeditorCenterView.style.height = viewHeight + 'px';

      let rodTopEle = this.$refs.rodTop;//获取顶部标尺
      let rodTopNum = Math.ceil(viewWidth / lineSpace);//根据当前画布宽度，计算格子数量
      //const rodTopCenterNum =  (375 * this.zoom / 100) / lineSpace;//中间视图已375像素为标准宽度，根据当前缩放比例，计算中间的刻度数量
      //const rodTopLeftNum = Math.round((rodTopNum - rodTopCenterNum) / 2);
      rodTopEle.width = viewWidth;
      rodTopEle.style['margin-left'] = '-' + (Math.ceil((viewWidth / 2)) + Math.floor(this.phoneWidth / 2)) + 'px';
      rodTopEle.height = rodEmptySize;
      let rodTop = rodTopEle.getContext('2d');//获取顶部标尺canvas
      rodTop.strokeStyle = '#666';//设置标尺线条颜色
      
      //处理顶部标尺，宽度750
      for (let i = 0; i < rodTopNum;i++) {
        rodTop.beginPath();//开始绘图
        rodTop.moveTo(i*lineSpace - 1 ,0);//移动到每格位置的顶部
        let lineLen = (i % 5 == 0) ? rodLineSizeLong : rodLineSizeShort;//长短不一的间隔线条
        if (i % 10 == 0) {
          //每10条即每50px设置一次长线条，并标记数字尺码
          lineLen = rodLineSizeText;
          rodTop.fillText((i -  rodTopNum / 2)* lineSpace * (this.zoom / 50),i*lineSpace  + 3,20);
        }
        rodTop.lineTo(i*lineSpace - 1 ,lineLen);//绘制线条
        rodTop.stroke();//完成并显示绘画
      }

 
      let rodLeftEle = this.$refs.rodLeft;
      let rodLeftNum = Math.ceil(viewHeight / lineSpace);
      rodLeftEle.width = rodEmptySize;
      rodLeftEle.height = viewHeight;
      let rodLeft = rodLeftEle.getContext('2d');
      rodLeft.strokeStyle = '#666';
      
      for (let i = 0; i < rodLeftNum;i++) {
        rodLeft.beginPath();
        rodLeft.moveTo(0,i*lineSpace - 1);
        let lineLen = (i % 5 == 0) ? rodLineSizeLong : rodLineSizeShort;
        
        if (i % 10 == 0) {
          lineLen = rodLineSizeText;
          rodLeft.save();
          rodLeft.translate(rodLineSizeText, i*lineSpace);
          rodLeft.rotate(270 * Math.PI / 180);
          rodLeft.fillText( (i - Math.round(initMarginTop / lineSpace)) * lineSpace * (this.zoom / 50),rodLineSizeText - 12,lineSpace + 4);
          rodLeft.restore();
        }

        
        rodLeft.lineTo(lineLen,i*lineSpace - 1);
        rodLeft.stroke();
        
      }
      
    },
    zoomFormatTip(val){
      return val + '%';
    },
    drawRod(){

    },
    getContentIndexById(id){
      return this.contentData.findIndex(item => item.id == id);
    },
    beforeUploadImg(file){

    },
    //组件名称点击
    tapCompName(){
      this.isEditCompName = true;
      this.$nextTick(()=>{
        this.$refs.compNameInput.focus();
      })
      
    },
    //组件名称失去焦点
    blurCompName(){
      this.isEditCompName = false;
    },
    uploadImgSuccess(id,res,file){
      console.log(id);
      let currentContentIndex = this.getContentIndexById(id);
      
      //判断当前选中的内容组件的类型，更新数据，刷新显示在中间预览
      switch(this.contentData[currentContentIndex].type) {
        case 'img' :
          this.$set(this.contentData[currentContentIndex].data, id,{url:file.url,name:file.name});
          break;
        case 'swiper':
            //判断是否已经存在值
            let attrArr = Object.keys(this.contentData[currentContentIndex].data);
            if (attrArr.length > 0) {
              this.contentData[currentContentIndex].data[id].list.push({url:file.url,name:file.name});
            } else {
              this.$set(this.contentData[currentContentIndex].data, id,{list:[{url:file.url,name:file.name}]});
            }
            break;
      }
      
    },
    tapRemoveImg(id,file){
      let currentContentIndex = this.getContentIndexById(id);
      for (let i in this.contentData[currentContentIndex].data) {
        console.log(this.contentData[currentContentIndex].data[i]);
        if (this.contentData[currentContentIndex].data[i].url == file.url) {
          this.contentData[currentContentIndex].data[i] = undefined;
        }
      }
    },
    tapPreviewImg(){
      console.log('preview');
    },
    //选中内容区的组件
    tapComponent(index){
      //let currentContentIndex = this.getContentIndexById(this.currentContentId);
      //if (index == currentContentIndex) return;
      //将表单内容的值显示成该组件的数据
      this.formData = this.contentData[index];

      return;
      if (this.contentData[index].data[this.contentData[index].id]) {
        if (this.contentData[index].type == 'img') {
          this.fileList = [this.contentData[index].data[this.contentData[index].id]];
        } else if (this.contentData[index].type == 'swiper'){
          this.fileList = this.contentData[index].data[this.contentData[index].id].list;
        }
        
      } else {
        this.fileList = [];
      }
      console.log(this.contentData[index].data[this.contentData[index].id]);
      //更新当前选中的组件标识
      this.currentContentId = this.contentData[index].id;
      console.log( this.contentData);
    },
    addNewComp(newComp){
      this.currentContentId = newComp.autoId;

      //给新组件的名称增加默认编号，如果之前编号已删除，则自动从小的开始填充
      let compNoArr = [];
      this.contentData.forEach(item=>{
        if (item.type == newComp.type) {
          compNoArr.push(item.compNo);
        }
      })
      console.log(compNoArr);
      compNoArr.sort((a,b)=>{return a - b});
      let compNoFind = 1;
      let compNoVal = 0;
      compNoArr.forEach(item=>{
        if (compNoVal === 0 && item != compNoFind) compNoVal = item;
        compNoFind++;
      })
      compNoVal = compNoVal ? compNoVal : compNoFind;
      newComp.compNo = compNoVal;
      newComp.name  = newComp.name + ' ' + compNoVal;
      this.contentData.push(newComp);
      this.tapComponent(this.contentData.length - 1);
    },
    onMove({ relatedContext, draggedContext }) {
      
      const relatedElement = relatedContext.element;
      const draggedElement = draggedContext.element;

      return (
        (!relatedElement || !relatedElement.fixed) && !draggedElement.fixed
      );
    },
    tapResetPosition(){
      this.$refs.dcpeditorCenter.scrollLeft = 1000;
      this.$refs.dcpeditorCenter.scrollTop = 1000;
      console.log(this.$refs.dcpeditorCenter);
    },
    moveView(e){
      this.$refs.rodTopMouse.style.left = (e.clientX - 276) + 'px';
      this.$refs.rodLeftMouse.style.top = (e.clientY - 50) + 'px';
    },
    moveoutView(){
      this.$refs.rodTopMouse.style.left = 0;
      this.$refs.rodLeftMouse.style.top = 0;
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 0,
        group: "description",
        disabled: false,//是否禁用拖动
        ghostClass: "ghost"
      };
    },
    listString() {
      return JSON.stringify(this.list, null, 2);
    },
  },
  watch: {
    zoom(newVal){
      this.init();
    },
    isDragging(newValue) {
      if (newValue) {
        this.delayedDragging = true;
        return;
      }
      this.$nextTick(() => {
        this.delayedDragging = false;
      });
    }
  }
};
</script>

<style scoped lang="scss">
$roleEmptySize:25px;

ul{padding:0;margin:0;}
li{list-style-type:none;}
.dcpeditor-wrapper{display: flex;justify-content: space-between;height:100%;width:100%;box-sizing: border-box;margin:0 auto;background: #fff;min-height:600px;}
.dcpeditor-left{width:276px;flex:0 0 276px;display:flex;flex-direction: column;box-sizing: border-box;border:2px solid #f0f2f5;}


.dcpeditor-center{
  background:#f0f2f5;width:100%;height:100%;overflow:auto;box-sizing: border-box;


 
  .dcpeditor-center-tool{
    display: flex;align-items: center;height:50px;

    .dcpeditor-center-tool-zoom{
      display: flex;
      align-items: center;
      width :400px;
    }
  }

  .rodtop-wrapper{
    display: flex;
    
  }
  
  
  .dcpeditor-center-main{
    display:flex;
    position:relative;
    height:calc(100% - 50px);
    overflow: hidden;

    .rodtop-position{flex:0 0 $roleEmptySize;width:$roleEmptySize;height:$roleEmptySize;background: #fff;cursor: pointer;position:absolute;left:0;top:0;z-index:5;}

    .rodtop{box-sizing: border-box;position:absolute;left:50%;top:0;z-index:2;}
    .rodleft{box-sizing: border-box;position:absolute;left:0;top:0;z-index:2;}

    .rodtop-mouse-line{position: absolute;z-index:3;top:0;left:0;height:15px;width:2px;background:#06f;}
    .rodleft-mouse-line{position: absolute;z-index:3;top:0;left:0;width:15px;height:2px;background:#06f;}

    
    .dcpeditor-center-view{
      width:100%;padding-top:100px;display:flex;justify-content: center;box-sizing: border-box;height:100%;overflow:auto;

      .dcpeditor-center-phone{
        background: #fff;width:375px;height:100%;
      }
    }
    
  }
}



.dcpeditor-right{
  width:320px;flex:0 0 320px;box-sizing:border-box;border:4px solid #f0f2f5;font-size:13px;padding-bottom:100px;

  .dcpeditor-form-group{border-bottom:1px solid #ccc;padding:10px;}

  .dcpeditor-form-label{padding-right:5px;}

  .dcpeditor-form-slider{cursor: e-resize;}

  .dcpeditor-form-name-wrapper{height:60px;}
  .dcpeditor-form-name{padding:10px 5px;border-bottom:1px solid #fff;}
  .dcpeditor-form-name:hover{border-bottom:1px solid #06f;cursor:text;}

  .dcpeditor-form-bottom{position: fixed;right:4px;bottom:0;width:312px;display: flex;justify-content: center;align-items: center;height:100px;border-top:1px solid #ccc;z-index:101;background: #fff;}

}


.ghost {opacity: 0.5;background: #c8ebfb;}
.phone-wrapper {width:100%;padding:0;}
.phone-item {cursor: move;}
.phone-item:hover{outline:2px solid #06f;}
.phone-item-active{outline:1px solid #06f;}
//如果是background的话，就再配合:hover :before使用
//.phone-item:hover{position: relative;}
//.phone-item:hover:before{content: '';position: absolute;top: -2px;left: -2px;bottom: -2px;right: -2px;border: 2px solid #06f;}


.el-carousel__item:nth-child(2n) {background-color: #99a9bf;}
.el-carousel__item:nth-child(2n+1) {background-color: #d3dce6;}

.comp-content-img{width:100%;height:100%;display: inline-block;background: #efefef;}


.no-img{width:100%;height:100%;display: flex;justify-content: center;align-items: center;}
/deep/ .editor-header{flex:0 0 40px;height:40px;width:100%;background:cornflowerblue;color:#fff;display: flex;justify-content: center;align-items: center;font-size:13px;}

.editor-content{padding:10px;}
</style>
